$(document).ready(function () {
//    if (sessionStorage.getItem('username') === null) {
//        $('#loginModal').modal('show');
//    }
//    setInterval(checkLogin(), 1000);
    $('#loginButton').click(function () {
        $('#loginForm').submit(function () {
            return false;
        });
        var username = $('#username').val();
        $.ajax({
            url: '/adminlogin',
            method: 'post',
            data: $('#loginForm').serialize(),
            dataType: 'json'
        }).done(function (data) {
            if (data.result === true) {
                $('#loginModal').modal('hide');
                sessionStorage.setItem('username', username);
                sessionStorage.setItem('token', data.token);
            } else {
                $('#loginForm').append($('<p>Username or password error</p>'));
                $('#loginModal').modal('show');
            }
        });
    });
    updateUsers();
    updateRoles();
    updateAuthorities();

    $('#user table').click(function (event) {
        if (event.target.nodeName.toLowerCase() === 'button') {
            $.ajax({
                url: '/deleteUser',
                method: 'post',
                data: {'userId': $(event.target).attr('data-id')}
            }).done(function () {
                updateUsers();
            });
        }
    });

    $('#role table').click(function (event) {
        if (event.target.nodeName.toLowerCase() === 'button') {
            $.ajax({
                url: '/deleteRole',
                method: 'post',
                data: {'roleId': $(event.target).attr('data-id')}
            }).done(function () {
                updateUsers();
                updateRoles();
            });
        }
    });

    $('#authority table').click(function (event) {
        if (event.target.nodeName.toLowerCase() === 'button') {
            $.ajax({
                url: '/deleteAuthority',
                method: 'post',
                data: {'authorityId': $(event.target).attr('data-id')}
            }).done(function () {
                updateUsers();
                updateRoles();
                updateAuthorities();
            });
        }
    });

    $('#addUserButton').click(function () {
        $('#addUserForm').submit(function () {
            return false;
        });
        $.ajax({
            url: '/addUser',
            method: 'post',
            data: $('#addUserForm').serialize(),
            dataType: 'json'
        }).done(function (data) {
            $('#addUserModal').modal('hide');
            updateUsers();
        })
    });

    $("button[data-target='#setRoleModal']").click(function () {
        $.ajax({
            url: '/getIdAndUsers',
            method: 'post',
            dataType: 'json'
        }).done(function (data) {
            var select = $('#setRoleUser');
            select.empty();
            for (key in data) {
                $('<option></option>').attr('value', data[key].id).html(data[key].username).appendTo(select);
            }
        });
        $.ajax({
            url: '/getIdAndRoles',
            method: 'post',
            dataType: 'json'
        }).done(function (data) {
            var select = $('#setRoleRole');
            select.empty();
            for (key in data) {
                $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(select);
            }
        });
    });

    $('#setRoleButton').click(function () {
        $('#setRoleForm').submit(function () {
            return false;
        });
        $.ajax({
            url: '/setRole',
            method: 'post',
            data: $('#setRoleForm').serialize(),
            dataType: 'json'
        }).done(function (data) {
            if (data.result === true) {
                $('#setRoleModal').modal('hide');
                updateUsers();
            } else {
                $('<p></p>').html('error').appendTo($('#setRoleForm'));
            }

        });
    });

    $('#addRoleButton').click(function () {
        $('#addRoleForm').submit(function () {
            return false;
        });
        $.ajax({
            url: '/addRole',
            method: 'post',
            data: $('#addRoleForm').serialize(),
            dataType: 'json'
        }).done(function () {
            $('#addRoleModal').modal('hide');
            updateRoles();
        });
    });

    $('button[data-target="#setLevelModal"]').click(function () {
        $.ajax({
            url: '/getIdAndRoles',
            method: 'post',
            dataType: 'json'
        }).done(function (data) {
            var high = $('#setLevelHigh');
            high.empty();
            var low = $('#setLevelLow');
            low.empty();
            for (key in data) {
                $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(high);
                $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(low);
            }
        });
    });

    $('#setLevelButton').click(function () {
        $('#setLevelForm').submit(function () {
            return false;
        });
        $.ajax({
            url: '/setLevel',
            method: 'post',
            data: $('#setLevelForm').serialize(),
            dataType: 'json'
        }).done(function (data) {
            if (data.result === true) {
                $('#setLevelModal').modal('hide');
            } else {
                $('<p></p>').html('error').appendTo($('#setLevelForm'));
            }
        });
    });

    $('button[data-target="#deleteLevelModal"]').click(function () {
        $.ajax({
            url: '/getIdAndRoles',
            method: 'post',
            dataType: 'json'
        }).done(function (data) {
            var high = $('#deleteLevelHigh');
            high.empty();
            $('<option></option>').appendTo(high);
            for (key in data) {
                $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(high);
            }
        });
    });

    $('#deleteLevelHigh').change(function () {
        $.ajax({
            url: '/getLowIdAndRoleByHighId',
            method: 'post',
            data: {highId: $(this).children('option:selected').val()},
            dataType: 'json'
        }).done(function (data) {
            var select = $('#deleteLevelLow');
            select.empty();
            for (key in data) {
                $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(select);
            }
        });
    });

    $('#deleteLevelButton').click(function () {
        $('#deleteLevelForm').submit(function () {
            return false;
        });

        $.ajax({
            url: '/deleteLevel',
            method: 'post',
            data: $('#deleteLevelForm').serialize(),
            dataType: 'json'
        }).done(function () {
            $('#deleteLevelModal').modal('hide');
            updateRoles();
            updateUsers();
        });
    });


    $('button[data-target="#setAuthorityModal"]').click(function () {
        $.ajax({
            url: '/getIdAndRoles',
            method: 'post',
            dataType: 'json'
        }).done(function (data) {
            var select = $('#setAuthorityRole');
            select.empty();
            for (key in data) {
                $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(select);
            }
        });

        $.ajax({
            url: '/getIdAndAuthorities',
            method: 'post',
            dataType: 'json'
        }).done(function (data) {
            var select = $('#setAuthorityAuthority');
            select.empty();
            for (key in data) {
                $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(select);
            }
        });
    });

    $('#setAuthorityButton').click(function () {
        $('#setAuthorityForm').submit(function () {
            return false;
        });
        $.ajax({
            url: '/setAuthority',
            method: 'post',
            data: $('#setAuthorityForm').serialize(),
            dataType: 'json'
        }).done(function (data) {
            if (data.result === true) {
                $('#setAuthorityModal').modal('hide');
                updateUsers();
                updateRoles();
            } else {
                $('<p></p>').html('error').appendTo($('#setAuthorityForm'));
            }
        });
    });

    $('button[data-target="#deleteRoleAuthorityModal"]').click(function () {
        $.ajax({
            url: '/getIdAndRoles',
            method: 'post',
            dataType: 'json'
        }).done(function (data) {
            var select = $('#deleteRoleAuthorityRole');
            select.empty();
            $('<option></option>').appendTo(select);
            for (key in data) {
                $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(select);
            }
        });

        $('#deleteRoleAuthorityRole').change(function () {
            $.ajax({
                url: '/getIdAndAuthoritiesByRoleId',
                method: 'post',
                data: {roleId: $(this).children('option:selected').val()},
                dataType: 'json'
            }).done(function (data) {
                var select = $('#deleteRoleAuthorityAuthority');
                select.empty();
                for (key in data) {
                    $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(select);
                }
            });
        });
    });

    $('#deleteRoleAuthorityButton').click(function () {
        $('#deleteRoleAuthorityForm').submit(function () {
            return false;
        });
        $.ajax({
            url: '/deleteRoleAuthority',
            method: 'post',
            data: $('#deleteRoleAuthorityForm').serialize(),
            dataType: 'json'
        }).done(function (data) {
            if (data.result === true) {
                $('#deleteRoleAuthorityModal').modal('hide');
                updateUsers();
                updateRoles();
            } else {
                $('<p></p>').html('error').appendTo($('#deleteRoleAuthorityForm'));
            }
        });
    });

    $('button[data-target="#setIncompatiblesModal"]').click(function () {
        $.ajax({
            url: '/getIdAndRoles',
            method: 'post',
            dataType: 'json'
        }).done(function (data) {
            console.log(data);
            var one = $('#setIncompatiblesOne');
            one.empty();
            var another = $('#setIncompatiblesAnother');
            another.empty();
            for (key in data) {
                $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(one);
                $('<option></option>').attr('value', data[key].id).html(data[key].name).appendTo(another);
            }
        });
    });

    $('#setIncompatiblesButton').click(function () {
        $('#setIncompatiblesForm').submit(function () {
            return false;
        });
        console.log($('#setIncompatiblesForm').serialize());
        $.ajax({
            url: '/setIncompatibles',
            method: 'post',
            data: $('#setIncompatiblesForm').serialize(),
            dataType: 'json'
        }).done(function (data) {
            if (data.result === true) {
                $('#setIncompatiblesModal').modal('hide');
            } else {
                $('<p></p>').html('error').appendTo($('#setIncompatiblesForm'));
            }

        });
    });

    $('#addAuthorityButton').click(function() {
        $('#addAuthorityForm').submit(function() {
            return false;
        });
        $.ajax({
            url: '/addAuthority',
            method:'post',
            data:$('#addAuthorityForm').serialize(),
            dataType:'json'
        }).done(function() {
            $('#addAuthorityModal').modal('hide');
            updateAuthorities();
        });
    });

    $('#refresh').click(function () {
        location.reload();
    });
});

function checkLogin() {
    $.ajax({
        url: '/adminCheckLogin',
        method: 'post',
        data: {
            username: sessionStorage.getItem('username'),
            token: sessionStorage.getItem('token')
        },
        dataType: 'json'
    }).done(function (data) {
        if (data.result !== true) {
            $('#loginModal').modal('show');
        }
    }).fail(function () {
        $('#loginModal').modal('show');
    });
}

function updateUsers() {
    $.ajax({
        url: '/getIdAndUsers',
        method: 'post',
        dataType: 'json'
    }).done(function (data) {
        var table = $('#user table tbody');
        table.empty();
        for (key in data) {
            var tr = $('<tr></tr>');
            tr.append($('<td></td>').html(data[key].username));
            tr.append($('<td></td>').html(data[key].roles.join(' ')));
            tr.append($('<td></td>').html(data[key].authorities.join(' ')));
            tr.append($('<td></td>').append($('<button class="btn"></button>').attr('data-id', data[key].id).html('delete')));
            table.append(tr);
        }
    });
}

function updateRoles() {
    $.ajax({
        url: '/getIdAndRoles',
        method: 'post',
        dataType: 'json'
    }).done(function (data) {
        var table = $('#role table tbody');
        table.empty();
        for (key in data) {
            var tr = $('<tr></tr>');
            tr.append($('<td></td>').html(data[key].name));
            tr.append($('<td></td>').html(data[key].own.join(' ')));
            tr.append($('<td></td>').html(data[key].inherit.join(' ')));
            tr.append($('<td></td>').append($('<button class="btn"></button>').attr('data-id', data[key].id).html('delete')));
            table.append(tr);
        }
    });
}

function updateAuthorities() {
    $.ajax({
        url: '/getIdAndAuthorities',
        method: 'post',
        dataType: 'json'
    }).done(function (data) {
        var table = $('#authority table tbody');
        table.empty();
        for (key in data) {
            var tr = $('<tr></tr>');
            tr.append($('<td></td>').html(data[key].name));
            tr.append($('<td></td>').append($('<button class="btn"></button>').attr('data-id', data[key].id).html('delete')));
            table.append(tr);
        }
    });
}